import { defineComponent, nextTick, reactive, ref, watch } from "vue";
import { Form, FormItem, Button, Modal } from "view-ui-plus";
import CustomLevel from "./customLevel";
import { onLevelSave } from "@/api/baseData/testProject";
import { VxeForm } from "vxe-table";

export default defineComponent({
  props: {
    modelValue: {
      type: Boolean,
      dafault: false,
    },
    projectId: String,
  },
  emits: ["update:modelValue", "change"],
  setup(props, { emit }) {
    const key = ref(0);
    watch(
      () => props.modelValue,
      () => {
        key.value = key.value + 1;
      }
    );

    const loading = ref(true);
    const form = ref(null);
    const modal = ref(null);
    const formValidate = reactive({
      level: [
        {
          compareTypeCode: "",
          resultRange: "",
          resultGrading: "",
          referenceStandard: "",
        },
      ],
    });

    const ruleValidate: any = reactive({
      level: [
        {
          required: true,
          message: "请填写完整",
          trigger: "change",
          validator(params) {
            return new Promise((resolve, reject) => {
              setTimeout(() => {
                const list = params.data.level;
                for (let index = 0; index < list.length; index++) {
                  const ele = list[index];
                  if (
                    !ele.compareTypeCode ||
                    !ele.resultRange ||
                    !ele.resultGrading ||
                    !ele.referenceStandard
                  ) {
                    reject(new Error("请填写完整"));
                    break;
                  }
                }
                resolve(true);
              });
            });
          },
        },
      ],
    });

    const resetValue = () => {
      formValidate.level = [
        {
          compareTypeCode: "",
          resultRange: "",
          resultGrading: "",
          referenceStandard: "",
        },
      ];
    };

    const handleSubmit = (name) => {
      form.value.validate((errMap) => {
        if (errMap) {
          form.value.validate();
          loading.value = false;
          nextTick(() => {
            loading.value = true;
          });
        } else {
          let params = formValidate.level.map((item) => ({
            ...item,
            projectId: props.projectId,
          }));
          onLevelSave(params).then((res) => {
            resetValue();
            form.value.reset();
            emit("change");
            emit("update:modelValue", false);
          });
        }
      });
    };

    const onCancel = () => {
      form.value.reset();
      emit("update:modelValue", false);
    };

    const formItems = [
      {
        field: "level",
        title: "",
        span: 24,
        slots: { default: "table" },
      },
    ];

    const renderTable = (params) => {
      return (
        <CustomLevel
          v-model={formValidate.level}
          onChange={() => form.value.updateStatus(params)}
        />
      );
    };

    return () => (
      <Modal
        ref={modal}
        model-value={props.modelValue}
        width={1100}
        title="添加检测子项目"
        onOnOk={handleSubmit}
        onOnCancel={onCancel}
        loading={loading.value}
      >
        {props.modelValue && (
          <VxeForm
            title-colon
            ref={form}
            title-width="180"
            titleAlign="right"
            data={formValidate}
            rules={ruleValidate}
            span={24}
            items={formItems}
            v-slots={{ table: renderTable }}
          ></VxeForm>
        )}
      </Modal>
    );
  },
});
